import os


def remove_spaces(directory):
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if ' ' in filename:
                old_path = os.path.join(root, filename)
                new_filename = filename.replace(' ', '_')  # 可以根据需求修改替换方式
                new_path = os.path.join(root, new_filename)

                os.rename(old_path, new_path)
                print(f'Renamed: {old_path} -> {new_path}')


def rename_files_in_directory(directory_path, prefix='new_name_', start_index=1, extension=None):
    """
    给指定目录下的所有文件（包含子文件）进行循环重命名。

    参数：
    - directory_path: 目标目录的路径
    - prefix: 重命名文件时添加的前缀
    - start_index: 文件的起始索引
    - extension: 指定要重命名的文件扩展名，如果为None，则重命名所有文件
    """
    for root, dirs, files in os.walk(directory_path):
        for filename in files:
            if extension is None or filename.lower().endswith(extension.lower()):
                # 构建新的文件名
                new_filename = f"{prefix}{start_index}" + ".jpg"
                start_index += 1

                # 构建文件的完整路径
                old_filepath = os.path.join(root, filename)
                new_filepath = os.path.join(root, new_filename)

                # 重命名文件
                os.rename(old_filepath, new_filepath)
                print(f'Renamed: {old_filepath} -> {new_filepath}')


if __name__ == "__main__":
    target_directory = 'test_AI测试图片/1221'  # 替换为目标目录的路径
    remove_spaces(target_directory)

    # 指定目录路径和重命名参数
    # directory_path_to_rename = target_directory
    # prefix_to_add = '蔬菜'
    # start_index_to_use = 1103800
    # extension_to_rename = None  # 设置为要重命名的文件扩展名，如 '.txt'，或者设置为 None 以重命名所有文件

    # 调用函数进行重命名
    # rename_files_in_directory(directory_path_to_rename, prefix_to_add, start_index_to_use, extension_to_rename)
